package com.ruoyi.project.utils;


import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;

public class RandomPasswordGenerator {
    private static final String LOWER_CASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String DIGITS = "0123456789";
    private static final String SPECIAL_CHARS = "!@#$%^&*()_-+=[]{}|:<>?,.";

    public static void main(String[] args) {
        int length = 10; // 生成密码的长度
        String password = generateRandomPassword(length);
        System.out.println(password);
    }

    public static String generateRandomPassword(int length) {
        StringBuilder password = new StringBuilder();
        Random random = new Random();

        // 生成至少一个小写字母
        password.append(getRandomCharacter(LOWER_CASE, random));

        // 生成至少一个大写字母
        password.append(getRandomCharacter(UPPER_CASE, random));

        // 生成至少一个数字
        password.append(getRandomCharacter(DIGITS, random));

        // 生成至少一个特殊字符
        password.append(getRandomCharacter(SPECIAL_CHARS, random));

        // 生成剩余的字符
        for (int i = 0; i < length - 4; i++) {
            String characters = LOWER_CASE + UPPER_CASE + DIGITS + SPECIAL_CHARS;
            password.append(getRandomCharacter(characters, random));
        }

        return password.toString();
    }

    private static char getRandomCharacter(String characters, Random random) {
        int index = random.nextInt(characters.length());
        return characters.charAt(index);
    }

    /**
     * 随机数
     * @param length
     * @return
     */
    public static String generateCode(int length) {
        SecureRandom secureRandom = new SecureRandom();
        byte[] randomBytes = new byte[length/2]; // 由于安全随机数是以字节为单位生成的，所以需要除以2
        secureRandom.nextBytes(randomBytes);
        BigInteger randomNumber = new BigInteger(1, randomBytes);
        return randomNumber.toString(10); // 将随机数转换为十六进制字符串
    }


    /**
     * 生成[min, max]之间的随机数
     */
    public static String generateSZCode() {
        int min = 100000, max = 999999;
        Random random = new Random();
        return String.valueOf(min + random.nextInt(max - min + 1));
    }
}